﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;
using System.Web.Caching;

using Enterprise.Model.User;
using Enterprise.Model.Role;
using Enterprise.Service.Role;
using Enterprise.Model.Module;
using Enterprise.Service.Module;
using Enterprise.Infrastructure;
namespace Enterprise.Service.User
{
    /// <summary>
    ///  用户权限服务应用
    /// </summary>
    public class UserPermissionService
    {
        #region "用户权限"
        private static Cache _UserPermissionCache = HttpRuntime.Cache;
        /// <summary>
        /// 根据用户ID,应用ID,PageCode判断用户是否拥有当前权限
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="ApplicationID"></param>
        /// <param name="PageCode"></param>
        /// <returns></returns>
        public static bool CheckPageCode(int UserId, int ApplicationId, string PageCode)
        {
            UserService uService = new UserService();
            if (uService.UserDisp(UserId).UADMIN == "1")//判断用户是否为超级用户
                return true;

            bool bBool = false;
            Hashtable UserPermission = Get_UserPermission(UserId);
            if (UserPermission.Count > 0)
            {
                string Key = string.Format("{0}-{1}", ApplicationId, PageCode);
                if (UserPermission.ContainsKey(Key))
                {
                    bBool = true;
                }
            }
            return bBool;
        }

        /// <summary>
        /// 根据用户ID,应用ID,PageCode,要检测权限数值
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="ApplicationID">应用ID</param>
        /// <param name="PageCode">PageCode</param>
        /// <param name="CheckPermissionValue">权限值</param>
        /// <returns></returns>
        public static bool CheckPageCode(int UserId, int ApplicationId, string PageCode, int CheckPermissionValue)
        {
            UserService uService = new UserService();
            if (uService.UserDisp(UserId).UADMIN == "1")//判断用户是否为超级用户
                return true;

            bool rBool = false;
            Hashtable UserPermission = (Hashtable)Get_UserPermission(UserId);
            if (UserPermission.Count > 0)
            {
                string Key = string.Format("{0}-{1}", ApplicationId, PageCode);
                if (UserPermission.ContainsKey(Key))
                {
                    if ((((RolePermissionEntity)UserPermission[Key]).PERMISSIONVALUE & CheckPermissionValue) == CheckPermissionValue)
                    {
                        rBool = true;
                    }
                }
            }

            return rBool;
        }

        /// <summary>
        /// 判断用户按钮权限
        /// </summary>
        /// <param name="PType"></param>
        /// <returns></returns>
        public static bool CheckButtonPermission(Utility.PopedomType PType)
        {
            PermissionEntity premission = Get_Permission;
            if (premission == null)
            {
                return true;
            }
            //返回用户判断信息
            bool rBool = false;
            rBool = CheckPageCode(Utility.Get_UserId, premission.ApplicationId, premission.PageCode, (int)PType);
            return rBool;

        }

        /// <summary>
        /// 当前目录下的权限设置
        /// </summary>
        private static PermissionEntity Get_Permission
        {
            get
            {
                return (PermissionEntity)ConfigurationManager.GetSection("PermissionEntity");
            }
        }

        /// <summary>
        /// 获取用户权限Hashtable
        /// </summary>
        /// <param name="UserId">用户ID</param>
        /// <returns></returns>
        private static Hashtable Get_UserPermission(int UserId)
        {
            string Key = string.Format("{1}-Permission-{0}", UserId, "Enterprise");
            if (_UserPermissionCache[Key] != null)
            {
                return (Hashtable)_UserPermissionCache[Key];
            }
            else
            {
                //根据用户Role取得模块权限列表
                Hashtable hashtable = (Hashtable)Get_RolePermissionTable(UserId);
                _UserPermissionCache.Insert(Key, hashtable);
                return hashtable;
            }

        }

        /// <summary>
        /// 根据用户ID,获取用户模块权限列表
        /// </summary>
        /// <param name="UserId">用户Id</param>
        /// <returns></returns>
        private static Hashtable Get_RolePermissionTable(int UserId)
        {
            Hashtable PageCodeList = new Hashtable();
            List<RolePermissionEntity> list = new List<RolePermissionEntity>();
            List<UserRoleEntity> userRoleList = UserRoleService.UserRoleList().Where(p => p.USERID == UserId).ToList();
            RolePermissionService rpService = new RolePermissionService();
            foreach (UserRoleEntity userRole in userRoleList)
            {
                List<RolePermissionEntity> query = rpService.RolePermissionList().Where(p => p.ROLEID == userRole.ROLEID).ToList();
                list.AddRange(query);
            }
            foreach (RolePermissionEntity rp in list)
            {
                string Key = string.Format("{0}-{1}", "1", rp.MCODE);
                if (PageCodeList.ContainsKey(Key))
                {
                    RolePermissionEntity Rpt = (RolePermissionEntity)PageCodeList[Key];
                    if (Rpt.PERMISSIONVALUE < rp.PERMISSIONVALUE)
                    {
                        PageCodeList[Key] = rp;
                    }
                }
                else
                {
                    PageCodeList.Add(Key, rp);
                }
            }
            return PageCodeList;

        }

        /// <summary>
        /// 移除用户权限Cache
        /// </summary>
        /// <param name="UserID">用户ID</param>
        public static void Move_UserPermissionCache(int UserId)
        {
            _UserPermissionCache.Remove(string.Format("{1}-Permission-{0}", UserId, "Enterprise"));
        }

        /// <summary>
        /// 移除某个角色的用户权限Cache
        /// 实现方法：通过RoleID遍历出所有的用户UserId，在循环删除各个UserId的_UserPermissionCache
        /// </summary>
        /// <param name="RoleID">角色ID</param>
        public static void Move_RoleUserPermissionCache(int RoleId)
        {
            var q = UserRoleService.UserRoleList().Where(p => p.ROLEID == RoleId);
            foreach (var var in q)
            {
                Move_UserPermissionCache(var.USERID);
            }
        }
        #endregion
    }
}
